<template>
  <div>
    <el-button @click="spuQueryMethod">刷新列表</el-button>
    <el-upload
        class="upload-excel"
        :action="uploadUrl"
        :on-success="handleSuccess"
        :on-error="handleError"
        :before-upload="beforeUpload"
        :headers="uploadHeaders"
        :show-file-list="true"
        accept=".xlsx,.xls"
        name="file"
    >
      <el-button type="primary">上传 Excel 文件</el-button>

      <el-select
          v-if="typeAll"
          v-model="currShop"
          @change="changeShop"
          placeholder="请选择商品"
          style="position: relative; left: 30%;"
      >
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </el-upload>

    <el-button
        type="success"
        @click="onTypechange"
        style="position: relative; left: 50%; top: -60px"
    >
      切换数据形势
    </el-button>

    <div>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="spuId" label="商品id" width="200"/>
        <el-table-column prop="spuName" label="商品名称" width="500"/>
        <el-table-column prop="price" label="售价" width="200"/>
        <el-table-column prop="cost" label="成本" width="200"/>
<!--        <el-table-column label="利润比例" width="100">-->
<!--          <template #default="{ row }">-->
<!--            &lt;!&ndash; 假设用退款金额 ÷ 销售金额 &ndash;&gt;-->
<!--            {{ row.price ? ((row.price / row.cost) * 100).toFixed(2) + '%' : '0%' }}-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'

import {spuQuery} from '/src/api/newsTop'

const apiBaseUrl = ref(import.meta.env.VITE_API_BASE_URL)
console.log('API Base URL:', apiBaseUrl.value) // 注意这里要用 .value
// 如果 token 存在，则将其加到请求头
const token = localStorage.getItem('token');
// 上传地址和请求头
const uploadUrl = apiBaseUrl.value + '/taoBaoData/spuImportTb'
const uploadHeaders = {
  Authorization: token
}

// 响应数据和状态管理
const tableData = ref([])
const options = ref([])
const currShop = ref('')
const allShopData = ref({})
const typeAll = ref(false)

// 上传前校验
const beforeUpload = (file) => {
  const isExcel =
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件（.xlsx/.xls）')
  }
  return isExcel
}

const spuQueryMethod = () => {
  let param = {
    pageNum: 1,
    pageSize: 1000

  }
  spuQuery(param).then(resp => {
    console.log(resp)
    tableData.value = resp.data.data
    console.log(tableData.value)
  })
}

// 上传成功回调
const handleSuccess = (response) => {
  ElMessage.success('上传成功')
  this.spuQueryMethod()
  // const shopArr = []

  // for (const key in response.data) {
  //   if (response.data.hasOwnProperty(key)) {
  //     const dataArr = response.data[key]
  //     if (dataArr[0]) {
  //       shopArr.push({
  //         label: dataArr[dataArr.length - 1].ProductTitle,
  //         value: key
  //       })
  //     }
  //   }
  // }
  // options.value = shopArr
  // allShopData.value = response
  //
  // if (!typeAll.value) {
  //   tableData.value = response.total
  // }

}

// 上传失败回调
const handleError = (err) => {
  ElMessage.error('上传失败')
  console.error('上传错误:', err)
}

// 切换商品时更新表格
const changeShop = (shop) => {
  console.log('选择的商品:', shop)
  tableData.value = allShopData.value.data[shop]
}

// 切换视图数据类型
const onTypechange = () => {
  typeAll.value = !typeAll.value
  if (!typeAll.value) {
    tableData.value = allShopData.value.total
  }
}
</script>

<style scoped>
.upload-excel {
  margin: 20px;
}
</style>
